package com.liuyang.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Constants;
import com.liuyang.common.Constast;
import com.liuyang.common.Result;
import com.liuyang.entity.Account;
import com.liuyang.entity.Interfaceinfo;
import com.liuyang.entity.Logs;
import com.liuyang.service.AccountService;
import com.liuyang.service.InterfaceinfoService;
import com.liuyang.service.LogsService;
import com.liuyang.utils.MapCacheManagerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class LoginController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private InterfaceinfoService interfaceinfoService;

    @PostMapping("/login")
    public Result login(String username, String password, String captcha, HttpSession session) {
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password) || StrUtil.isEmpty(captcha)) {
            throw new RuntimeException(Constast.PARAMETER_NULL);
        }
        // 进行验证码判断
        String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(!StrUtil.equalsIgnoreCase(captcha, code)) {
            return Result.fail("验证码错误");
        }

        Account account = accountService.getOne(new QueryWrapper<Account>().eq("accountName", username).eq("accountPassword", SecureUtil.md5(password)));

        // 读取系统模块信息
        List<Interfaceinfo> interfaceinfoList = interfaceinfoService.list();
        Map interfaceInfoMap = interfaceinfoList.stream().collect(Collectors.toMap(Interfaceinfo::getInterfaceUrl, Interfaceinfo::getInterfaceName));
        MapCacheManagerUtils.getInstance().setMapCache(interfaceInfoMap); // 设置系统模块缓存

        if(ObjectUtil.isNull(account)) {
            return Result.fail("账号不正确");
        }
        if(StrUtil.equals(account.getAccountStatus(), "0")) {
            return Result.fail("账号被禁用");
        }

        MapCacheManagerUtils.getInstance().setUserAccount(account.getAccountName()); // 设置账号名
        session.setAttribute("account", account);
        return Result.succ(200, "登录成功", account);
    }
}
